package com.yimiyisu.contract_cust.kit;

import com.yimiyisu.contract_cust.domain.CodeRulesDO;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class CodeKit {

    // 存储每个重置规则的当前序列号
    private static final Map<String, Integer> sequenceMap = new HashMap<>();
    // 重置规则键前缀
    private static final String SEQUENCE_KEY_PREFIX = "SERIAL_";

    public static String generateCode(CodeRulesDO rules) {

        // 1. 生成日期部分
        String datePart = generateDatePart(rules.getDate());

        // 2. 获取序列号（根据重置规则）
        String sequenceKey = getSequenceKey(rules.getResetRule(), datePart);
        int sequence = sequenceMap.compute(sequenceKey, (k, v) -> (v == null) ? 1 : v + 1);
        String sequencePart = String.format("%0" + rules.getNumber() + "d", sequence);

        // 3. 确定连接符
        String conn = getConnectorSymbol(rules.getConnector());

        // 4. 根据顺序组合元素
        return assembleCode(rules.getHeader(), datePart, sequencePart, conn, rules.getOrder());
    }

    private static String generateDatePart(int dateFormat) {
        LocalDate now = LocalDate.now();
        return switch (dateFormat) {
            case 1 -> DateTimeFormatter.ofPattern("yyyy").format(now);   // 年
            case 2 -> DateTimeFormatter.ofPattern("yyyyMM").format(now); // 年月
            case 3 -> DateTimeFormatter.ofPattern("yyyyMMdd").format(now); // 年月日
            default -> throw new IllegalArgumentException("无效日期格式");
        };
    }

    private static String getSequenceKey(int resetRule, String datePart) {
        return SEQUENCE_KEY_PREFIX + switch (resetRule) {
            case 1 -> datePart.substring(0, 4);  // 按年重置
            case 2 -> datePart.substring(0, 6);  // 按月重置
            case 3 -> datePart;                  // 按日重置
            default -> throw new IllegalArgumentException("无效重置规则");
        };
    }

    private static String getConnectorSymbol(int connector) {
        return switch (connector) {
            case 0 -> "";
            case 1 -> "/";
            case 2 -> "-";
            case 3 -> "_";
            default -> "";
        };
    }

    private static String assembleCode(String header, String date, String seq, String conn, int order) {
        return switch (order) {
            // 已添加所有6种排序规则
            case 1 -> header + conn + date + conn + seq;    // 开头字母+日期+流水号
            case 2 -> header + conn + seq + conn + date;    // 开头字母+流水号+日期
            case 3 -> date + conn + header + conn + seq;    // 日期+开头字母+流水号
            case 4 -> date + conn + seq + conn + header;    // 日期+流水号+开头字母
            case 5 -> seq + conn + header + conn + date;    // 流水号+开头字母+日期
            case 6 -> seq + conn + date + conn + header;    // 流水号+日期+开头字母
            default -> throw new IllegalArgumentException("无效排序规则");
        };
    }
}
